var express = require('express')
var router = express.Router()

let usersList = [
    {userName: "admin123", password: 'admin123'}
]

router.get('/list', function (req, res, next) {
    res.send(usersList)
})

router.post('/login', function (req, res, next) {
    let index = usersList.findIndex(item => {
        return req.body.userName === item.userName && req.body.password === item.password
    })

    if (index >= 0) {
        res.send({
            msg: '登录成功',
            code: 200
        })
    } else {
        res.send({
            msg: '登录失败',
            code: 500
        })
    }
})

router.post('/register', function (req, res, next) {
    if (!req.body.userName || !req.body.password) {
        res.send('请输入账号或密码')

        return
    }

    let data = {
        userName: req.body.userName,
        password: req.body.password
    }

    usersList.push(data)

    res.send({
        msg: '注册成功',
        code: 200,
        data: true
    })
})

router.put('/update', function (req, res, next) {
    if (!req.body.userName) {
        res.send('无法找到该用户')

        return
    }

    if (!req.body.password) {
        res.send('请输入新密码')

        return
    }

    let index = usersList.findIndex(item => {
        return String(item.userName) === String(req.body.userName)
    })

    if (index < 0) {
        res.send({
            msg: '修改密码失败，未通过userName找到对应用户',
            code: 500,
            data: false
        })

        return
    }

    usersList[index] = Object.assign({}, req.body)

    res.send({
        msg: '修改密码成功',
        code: 200,
        data: true
    })
})

router.delete('/delete', function (req, res, next) {
    if (!req.body.userName) {
        res.send('无法找到该用户')

        return
    }

    let index = usersList.findIndex(item => {
        return String(item.userName) === String(req.body.userName)
    })

    if (index < 0) {
        res.send({
            msg: '删除用户失败，未能通过userName找到对应用户',
            code: 500,
            data: false
        })
        return
    }

    dormitoryData.splice(index, 1)

    res.send({
        msg: '删除用户成功',
        code: 200,
        data: true
    })
})

module.exports = router